﻿using Medhurst.Unity.Configuration.Models;
using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Medhurst.Unity.Configuration
{
    /// <summary>
    /// Factory method for loading configuration files.
    /// </summary>
    internal sealed class YamlConfigLoadFactory
    {
        public string AliasesPath { get; private set; }
        public string BehavioursPath { get; private set; }
        public Aliases LoadedAliases { get; set; }
        public Behaviours LoadedBehaviours { get; set; }

        /// <summary>
        /// Convert files names into paths or set <see cref="UseXmlConfiguration"/> instead.
        /// </summary>
        internal YamlConfigLoadFactory WithFileNames(string aliasesFileName, string behavioursFileName)
        {
            // normalise aliases
            if (String.IsNullOrEmpty(aliasesFileName))
                AliasesPath = "aliases.yaml";
            else
                AliasesPath = aliasesFileName;

            // normalise behaviours
            if (String.IsNullOrEmpty(behavioursFileName))
                BehavioursPath = "behaviours.yaml";
            else
                BehavioursPath = behavioursFileName;

            return this;
        }

        /// <summary>
        /// Load configuration from files.
        /// </summary>
        internal YamlConfigLoadFactory LoadFromFiles()
        {
            // try and load aliases
            LoadedAliases = Aliases.LoadFile(AliasesPath);

            // try and load behaviours
            LoadedBehaviours = Behaviours.LoadFile(BehavioursPath);

            return this;
        }

        /// <summary>
        /// Process the behaviours parsed through unity.
        /// </summary>
        internal YamlConfigLoadFactory ProcessBehaviours(IUnityContainer unity)
        {
            // make changes to container from files
            new YamlUnityAdapter(this).Fill(unity);

            return this;
        }
    }
}
